use reqwest::blocking::Client;
use serde::{Serialize, Deserialize};
use std::error::Error;

/// 创建 PR 时发送的请求体
#[derive(Serialize)]
struct CreatePrRequest<'a> {
    title: &'a str,
    head: &'a str,
    base: &'a str,
    body: &'a str,
}

/// 创建 PR 后返回的关键字段
#[derive(Deserialize)]
struct CreatePrResponse {
    number: u64,
    html_url: String,
}

pub struct CreatedPr {
    pub number: u64,
    pub url: String,
}

/// 调用 Gitee API 创建 PR，成功返回 PR 编号
pub fn create_pr(
    owner: &str,
    repo: &str,
    token: &str,
    title: &str,
    head: &str,
    base: &str,
    body: &str,
) -> Result<CreatedPr, Box<dyn Error>> {
    let url = format!("https://gitee.com/api/v5/repos/{}/{}/pulls", owner, repo);
    let client = Client::new();

    let req_body = CreatePrRequest {
        title,
        head,
        base,
        body,
    };

    let res = client
        .post(&url)
        .query(&[("access_token", token)])
        .json(&req_body)
        .send()?;

    if res.status().is_success() {
        let response: CreatePrResponse = res.json()?;
        println!("✅ PR #{} 创建成功！", response.number);
        println!("🔗 链接: {}", response.html_url);

        // ✅ 自动打开 PR 页面
        if webbrowser::open(&response.html_url).is_ok() {
            println!("🌐 已在浏览器打开 PR 页面");
        }

        Ok(CreatedPr {
            number: response.number,
            url: response.html_url,
        })
    } else {
        let err_text = res.text()?;
        if err_text.contains("已经存在相同的 Pull Request") {
            return Err("⚠️ 已存在相同分支的 Pull Request（即使已关闭）".into());
        }

        Err(format!("Gitee API 错误：{}", err_text).into())
    }
}

/// 向指定 PR 添加评论
pub fn comment_pr(
    owner: &str,
    repo: &str,
    pr_number: u64,
    token: &str,
    comment: &str,
) -> Result<(), Box<dyn Error>> {
    let url = format!(
        "https://gitee.com/api/v5/repos/{}/{}/pulls/{}/comments",
        owner, repo, pr_number
    );

    let client = Client::new();

    let res = client
        .post(&url)
        .query(&[("access_token", token)])
        .json(&serde_json::json!({
            "body": comment,
        }))
        .send()?;

    if res.status().is_success() {
        println!("💬 评论发送成功！");
        Ok(())
    } else {
        let err_text = res.text()?;
        Err(format!("❌ 评论失败: {}", err_text).into())
    }
}
